package com.sdry.good.logistics.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sdry.basic.entity.Mainframe;
import com.sdry.basic.entity.Material;
import com.sdry.basic.service.MainframeService;
import com.sdry.basic.service.MaterialService;
import com.sdry.good.logistics.entity.ReportDeficiencyOrderDetail;
import com.sdry.good.logistics.service.ReportDeficiencyOrderDetailService;
import com.sdry.system.entity.SysUser;
import com.sdry.untils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import java.io.PrintWriter;
import java.util.Date;
import com.sdry.good.logistics.entity.ReportDeficiencyOrder;
import com.sdry.good.logistics.service.ReportDeficiencyOrderService;
import com.sdry.good.logistics.mapper.ReportDeficiencyOrderMapper;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 *
 *@ClassName: ReportDeficiencyOrderController
 *@Description: 报缺明细单表
 *@Author tdd
 *@Date 2020-03-30 16:52:49
 *@version 1.0
*/
@Controller
@RequestMapping("/reportDeficiencyOrder")
public class ReportDeficiencyOrderController{


	@Resource ReportDeficiencyOrderService reportDeficiencyOrderService;
	@Resource ReportDeficiencyOrderDetailService reportDeficiencyOrderDetailService;
	@Resource
	MaterialService materialService;
	@Resource
	MainframeService mainframeService;
	//声明一个Logger
	private final static Logger logger = LoggerFactory.getLogger(ReportDeficiencyOrderController.class);
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public String pageReportDeficiencyOrder (Model model) {
		return "/td/logistics/reportDeficiencyOrder";
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public ReportDeficiencyOrder queryById(Long id) {
		logger.info("id"+id);
		ReportDeficiencyOrder param = reportDeficiencyOrderService.queryById(id);
		logger.info("根据主键id查询实体返回内容"+JSONArray.fromObject(param));
		return param;
	}
	/** 
	 * 根据条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<ReportDeficiencyOrder> queryAllByMution(ReportDeficiencyOrder param) {
		logger.info("根据条件查询所有条件"+JSONArray.fromObject(param));
		List<ReportDeficiencyOrder> list = reportDeficiencyOrderService.queryAllByMution(param);
		logger.info("根据条件查询所有返回内容"+JSONArray.fromObject(list));
		return list;
	}
	/** 
	 * 根据条件分页查询
	 * @param param 实体条件
	 * @param response
	*/
	@RequestMapping("/orderList")
	public void orderList(ReportDeficiencyOrder param,HttpServletResponse response){
		logger.info("根据条件分页查询条件"+JSONArray.fromObject(param));
		/*
		 * 条件分页查询内容
		 */
		List<ReportDeficiencyOrder> list = reportDeficiencyOrderService.findPageByMution(param);
		logger.info("根据条件分页查询条件返回内容"+JSONArray.fromObject(list));
		/*
		 * 条件查询总条数
		 */
		Integer total = reportDeficiencyOrderService.selectCountByMution(param);
		logger.info("条件查询总条数返回条数"+total);
		/*
		 * 转为json数据传至页面
		 */
		//创建result
		JSONObject jsonObject = new JSONObject();
		//添加入jsonObject
		jsonObject.put("code", 0);
		jsonObject.put("rows", list);
		jsonObject.put("total", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("根据条件分页查询返回数据失败");
			e.printStackTrace();
		}
	}


	/**
	 * 根据条件分页查询
	 * @param param 实体条件
	 * @param response
	 */
	@RequestMapping("/orderDetailList")
	public void orderDetailList(ReportDeficiencyOrderDetail param, HttpServletResponse response){
		logger.info("根据条件分页查询条件"+JSONArray.fromObject(param));
		/*
		 * 条件分页查询内容
		 */
		List<ReportDeficiencyOrderDetail> list = reportDeficiencyOrderDetailService.findPageByMution(param);
		logger.info("根据条件分页查询条件返回内容"+JSONArray.fromObject(list));
		/*
		 * 条件查询总条数
		 */
		Integer total = reportDeficiencyOrderDetailService.selectCountByMution(param);
		logger.info("条件查询总条数返回条数"+total);
		/*
		 * 转为json数据传至页面
		 */
		//创建result
		JSONObject jsonObject = new JSONObject();
		//添加入jsonObject
		jsonObject.put("code", 0);
		jsonObject.put("rows", list);
		jsonObject.put("total", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("根据条件分页查询返回数据失败");
			e.printStackTrace();
		}
	}


	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	*/
	@RequestMapping("/insert")
	public void insert(ReportDeficiencyOrder param, HttpServletResponse response){
		logger.info("插入返回id插入内容"+JSONArray.fromObject(param));
		Long id = reportDeficiencyOrderService.insert(param);
		logger.info("插入返回id"+id);
		try {
			ResponseUtil.write(response,id);
		} catch (Exception e) {
			logger.info("插入返回id返回数据失败");
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	*/
	@RequestMapping("/update")
	public void update(ReportDeficiencyOrder param,HttpServletResponse response){
		logger.info("根据主键更新 返回影响行数更新内容"+JSONArray.fromObject(param));
		Integer count = reportDeficiencyOrderService.update(param);
		logger.info("根据主键更新 返回影响行数"+count);
		try {
			ResponseUtil.write(response,count);
		} catch (Exception e) {
			logger.info("根据主键更新 返回影响行数返回数据失败");
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response){
		logger.info("根据主键拼接的字符串删除返回影响行数：主键拼接"+ids);
		ids=ids.replace("'",""); 
		Integer count = reportDeficiencyOrderService.delete(ids);
		logger.info("根据主键拼接的字符串删除返回影响行数"+count);
		try {
			ResponseUtil.write(response,count);
		} catch (Exception e) {
			logger.info("根据主键拼接的字符串删除返回影响行数返回数据失败");
			e.printStackTrace();
		}
	}


	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		logger.info("导入Excel");
		String uplodeFile = UrlUtil.UPLODE_FILE;
        File fileBao =new File(uplodeFile);
        //如果文件夹不存在则创建
        if  (!fileBao .exists()  && !fileBao.isDirectory())
        {
            System.out.println("//不存在");
            fileBao .mkdir();
        }
        String savePath = uplodeFile+DateUtil.dateFormat4()+file.getOriginalFilename();
		File newFile=new File(savePath);

		//通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		try {
			file.transferTo(newFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//取文件后缀
		String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
		System.out.println(subfix);
		List<List<String>> lists = new ArrayList<>();
		int num = 6;
		if(subfix.equals("xls")){
			try {
				lists = ExcelUtils.readXls(savePath, request, num);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else if(subfix.equals("xlsx")){
			try {
				lists = ExcelUtils.readXlsx(savePath, request,num);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				response.getWriter().print("0");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		int flag = 1;
		if (lists != null && lists.size() > 2 && !"".equals(lists.get(0).get(0).trim()) && null != lists.get(0).get(0).trim()) {
			//用户
			SysUser user = (SysUser) request.getSession().getAttribute("user");
			//数据
			List<String> list0= lists.get(0);
            ReportDeficiencyOrder reportDeficiencyOrder = new ReportDeficiencyOrder();
            //判断获取主机厂
			Mainframe mainframe = new Mainframe();
			mainframe.setMname(list0.get(0).trim());
            List<Mainframe> mainframes = mainframeService.queryAllByMution(mainframe);
            if(mainframes.size() == 1){
                reportDeficiencyOrder.setMainframeId(mainframes.get(0).getMid());
                reportDeficiencyOrder.setRemark1(list0.get(1).trim());
                reportDeficiencyOrder.setRdoNumber(DateUtil.dateFormat4());
                reportDeficiencyOrder.setCreateDate(DateUtil.dateFormat3());
				reportDeficiencyOrder.setCreateBy(user.getUsername());
				reportDeficiencyOrder.setDelFlag("0");
                Long rdoId = reportDeficiencyOrderService.insert(reportDeficiencyOrder);
                ReportDeficiencyOrderDetail reportDeficiencyOrderDetail = new ReportDeficiencyOrderDetail();
                reportDeficiencyOrderDetail.setRdoId(rdoId);
                int del = 0;
                for (int i = 2; i < lists.size(); i++) {
                    List<String> list= lists.get(i);
                    Material materiel = new Material();
                    if(null != list.get(0) && !"".equals(list.get(0))) {
                        materiel.setMaNumber(list.get(0).trim());
                        List<Material> ms=materialService.queryAllByMution(materiel);
                        if(ms.size() == 1){
                            reportDeficiencyOrderDetail.setMaId(ms.get(0).getMaId());
                            reportDeficiencyOrderDetail.setRdodNum(StringUtil.strNum(list.get(2).trim()));
                            reportDeficiencyOrderDetail.setDemandTime(list.get(3).trim());
                            if(null != list.get(4)){
								reportDeficiencyOrderDetail.setRemark1(list.get(4).trim());
							}
                            reportDeficiencyOrderDetail.setUrgency(list.get(5).trim());
                            long affact = reportDeficiencyOrderDetailService.insert(reportDeficiencyOrderDetail);
                            if (affact == 0) {
                                flag = 0;
                                break;
                            }
							del++;
                        }else{
                            flag = -2;
                            break;
                        }
                    } else {
                        flag = -1;
                        break;
                    }
                }
                if(del ==0){
					reportDeficiencyOrderService.delete(rdoId+"");
				}
            }else{
                flag = -2;
            }
		}else{
			flag = -1;
		}
		try {
			newFile.delete();// 删除
			response.getWriter().print(flag);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
